package demo2;

import java.math.BigInteger;
import java.util.*;

//链表相加(二)
class ListNode {
   int val;
   ListNode next = null;
   public ListNode(int val) {
     this.val = val;
   }
 }


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int k = 0;//进制
        while(cur1!=null || cur2!=null) {
            int a = cur1 == null ? 0 : cur1.val;
            int b = cur2 == null ? 0 : cur2.val;
            //System.out.println(a+b);
            ListNode node = new ListNode((a+b+k)%10);
            k = (a+b+k)/10;
            cur.next = node;
            cur = cur.next;
            if(cur1!=null) {
                cur1 = cur1.next;
            }
            if(cur2!=null) {
                cur2 = cur2.next;
            }
        }
        if(k!=0) {
            ListNode node = new ListNode(k);
            cur.next = node;
        }

        head = reverse(head.next);
        return head;
    }
    public ListNode reverse(ListNode head) {
        ListNode newHead = new ListNode(-1);
        ListNode cur = head;
        while(cur!=null) {
            ListNode next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;
            cur = next;
        }
        return newHead.next;
    }
}
